import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
//碰撞

// import * as dat from 'dat.gui'
// 导入dat.gui库
// import * as dat from 'dat.gui'

export const threes = {
  data() {
    return {
      baseUrl: 'https://zfatt.oss-cn-beijing.aliyuncs.com/experiment/zk/',
      cameras: null,
      planeTop: null,
      planeBottom: null,
      cylinder: null,
      scale: 0,
      translateX: 0,
      translate: 0,
      theWidth: 1,
      theHeight: 1,
      params: {
        // 存储参数
        topPlaneX: -0.68,
        topPlaneY: 1.5,
        topPlaneZ: -0.15,
        bottomPlaneX: -0.68,
        bottomPlaneY: 0.84,
        bottomPlaneZ: -0.15
      },
      geometryTop: null,
      geometryBottom: null,
      XianShuChuiZhiCeShiTong_1: null,
      ZhunZhiDuJianCeBan: null,
      PingBanTanCeQi: null,
      cameraOriginal: [-4.51, 1.456, 0.574],
      objectNames: [
        'ShiYanShi1_2',
        'ShiYanShi1_3',
        'ShiYanShi1_4',
        'TanCeQi4',
        'ZhuanHuanQi9',
        'DR7_2' //
      ],
      //气泡对应名称
      objectText: [
        { name: 'TanCeQi4', text: '圆柱体' },
        { name: 'ZhuanHuanQi9', text: 'ZhuanHuanQi9' },
        { name: 'ShiYanShi1_4', text: 'ShiYanShi1_4' },
        {
          name: 'DR7_2',
          text: 'DR7_2'
        },
        {
          name: 'ShiYanShi1_2',
          text: 'ShiYanShi1_2'
        },
        {
          name: 'ShiYanShi1_3',
          text: 'ShiYanShi1_3'
        }
      ],
      DR7_2: '',
      playIng: false,
      camera: null,
      scene: null,
      render: null,
      raycaster: null,
      mouse: null,
      objects: [],
      objectFather: null,
      action: null,
      andh: null,
      objectReItem: null,
      dhfiles: ['DRDH.glb'],
      isDestroyed: false,
      animationFrameId:null
    }
  },

  created() {},
  mounted() {},
  beforeDestroy() {
    // clearTimeout()
    // try {
    //   this.scene.clear()
    //   this.render.dispose()
    //   this.render.forceContextLoss()
    //   this.render.content = null
    //   // cancelAnimationFrame(animationID) // 去除animationFrame
    //   const gl = this.render.domElement.getContext('webgl')
    //   gl && gl.getExtension('WEBGL_lose_context').loseContext()
    // } catch (e) {
    //   console.log(e)
    // }
     this.clearAll()
  },
  watch: {
    theWidth() {
      console.log('监听到值变化')
      this.getLine(true)
      this.planeTop.visible = true
      this.cylinder.visible = true
      this.planeBottom.visible = true
      //  this.animate()
    },
    theHeight() {
      console.log('监听到值变化2')
      this.getLine(true)
      //  this.animate()
      this.planeTop.visible = true
      this.cylinder.visible = true
      this.planeBottom.visible = true
    }
  },
  computed: {
    getPosition() {
      //根据返回的位置信息计算物品提示小标位
      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      let leftPercentage = ((this.tipPosition.x + 25) / maincontWidth) * 100
      let topPercentage = ((this.tipPosition.y - 30) / maincontHeight) * 100
      return 'left:' + leftPercentage + '%;top:' + topPercentage + '%;'
    }
  },
  methods: {
     clearAll() { 
        clearInterval(this.spriteTimer)
        this.spriteTimer = null

  
      try {
               // 清理所有定时器
      // clearTimeout()
       // 标记销毁，停止动画
        this.isDestroyed = true
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId)
        this.animationFrameId = null
      }
        //销毁sprite
          // this.clearPoint()
      // 停止所有动画
      if (typeof this.stopall === 'function') this.stopall()
      // 清理动画状态
      this.animationStatus = {}
      this.mixerMap = {}
      if (this.theMixer) {
        this.theMixer.stopAllAction()
        if (this.objectFather && this.objectFather.scene) {
          this.theMixer.uncacheRoot(this.objectFather.scene)
        }
        this.theMixer = null
      }
      if (this.action) {
        this.action.stop()
        this.action.reset()
        this.action = null
      }

      // 清理场景中的所有对象
      if (this.scene) {
        this.scene.traverse((child) => {
          if (child.isMesh) {
            if (child.geometry) child.geometry.dispose()
            if (child.material) {
              if (Array.isArray(child.material)) {
                child.material.forEach(material => {
                  if (material.map) material.map.dispose()
                  if (material.lightMap) material.lightMap.dispose()
                  if (material.bumpMap) material.bumpMap.dispose()
                  if (material.normalMap) material.normalMap.dispose()
                  if (material.specularMap) material.specularMap.dispose()
                  if (material.envMap) material.envMap.dispose()
                  material.dispose()
                })
              } else {
                if (child.material.map) child.material.map.dispose()
                if (child.material.lightMap) child.material.lightMap.dispose()
                if (child.material.bumpMap) child.material.bumpMap.dispose()
                if (child.material.normalMap) child.material.normalMap.dispose()
                if (child.material.specularMap) child.material.specularMap.dispose()
                if (child.material.envMap) child.material.envMap.dispose()
                child.material.dispose()
              }
            }
          }
          if (child.isLight) { // 添加对灯光的处理
      child.dispose(); // 释放灯光资源
          }
          if (child.texture) { 
            child.texture.dispose();
          }
        })
        this.scene.clear()
      }
      // 清理渲染器
      if (this.render) {
        this.render.dispose()
        this.render.forceContextLoss()
        // 清理WebGL上下文
        if (this.render.domElement) {
          const gl = this.render.domElement.getContext('webgl')
          if (gl) {
            const loseContext = gl.getExtension('WEBGL_lose_context')
            if (loseContext) loseContext.loseContext()
          }
        }
        // 移除DOM
        if (this.$el && this.render.domElement && this.$el.contains(this.render.domElement)) {
          this.$el.removeChild(this.render.domElement)
        }
        this.render = null
      }
      // 清理相机
      this.camera = null

      // 清理控制器
      if (this.controls && typeof this.controls.dispose === 'function') {
        this.controls.dispose()
      }
      this.controls = null
      // 清理射线检测器
      this.raycaster = null
      // 清理鼠标对象
      this.mouse = null
      // 清理时钟
      this.clock = null
      // 清理对象引用
      this.objects = []
      this.objectFather = null
      this.objectFatherscene = null
      this.model = null
    
      this.outlinePass = null
      this.composer = null
      // 移除事件监听器
      if (document.body) {
        document.body.removeEventListener('mousemove', this.onDocumentMouseMove)
        document.body.removeEventListener('mousedown', this.onDocumentMouseDown)
      }
      if (this.$el) {
        this.$el.removeEventListener('mouseup', this.onDocumentMouseUp)
      }
      if (window) {
        window.removeEventListener('resize', this.onWindowResize)
      }
      this.isDestroyed  = false
    } catch (e) {
      console.log('清理资源时发生错误:', e)
      
    }
    },
           // 立即停止所有正在播放的动画，并设置为播放完成状态
    stopall() {
   
      console.log('执行了停止动画');
      
      if (!this.theMixer || !this.action) return;
      // 只 stop，不 reset，clampWhenFinished=true 保证停在最后一帧
      this.action.stop();
      this.playIng = false;
      if (!this.animationStatus) this.animationStatus = {};
      // 标记当前动画为已完成
      if (this.action._clip && this.action._clip.name) {
        this.animationStatus[this.action._clip.name] = true;
      }

        if (this.action._clip) {
        this.action.time = this.action._clip.duration;
        this.action.paused = true;
        this.theMixer.update(0); // 立即刷新到最后一帧
      }
    },
    //初始化
    init() {
      this.initSence()
      this.raycaster = new THREE.Raycaster() // 设置光线拾取
      this.clock = new THREE.Clock()
      this.mouse = new THREE.Vector2()
    },
    //初始化相机
    initCeremar() {
      const camera = new THREE.PerspectiveCamera(
        50,
        window.innerWidth / window.innerHeight,
        0.01,
        10000
      )
      camera.position.set(
        this.cameraOriginal[0],
        this.cameraOriginal[1],
        this.cameraOriginal[2]
      )

      this.camera = camera
      this.scene.add(this.camera)
      this.cameras = this.camera
      this.move(
        [0.362, 1.539, -4.092],
        [179.24 / 180, -0.75 / 180, 179.99 / 180]
      )
      // this.
    },
    //初始化场景
    initSence() {
      var scene = new THREE.Scene()
      scene.background = new THREE.Color(0xffffff)
      this.scene = scene
      this.getTop()
      this.initLight()
      this.initCeremar()
      this.initRenderer()
      this.initCotronl()
      this.initPoint()
      // this.animate(); //刷新场景
      this.initFile()
      // this.initGUI()
      this.initFileS(0)
    },

    //初始化渲染器
    initRenderer() {
      //   this.render = new THREE.WebGLRenderer({
      //     antialias: true,
      //     logarithmicDepthBuffer: true
      //   })
      //   this.render.setClearColor(0xaaaaaa);
      //   this.render.setPixelRatio(window.devicePixelRatio)
      //    this.render.setSize(window.innerWidth, window.innerHeight)
      //   this.render.shadowMap.enabled = true
      //   this.render.shadowMap.type = THREE.PCFShadowMap;
      // this.render.outputColorSpace = THREE.SRGBColorSpace
      //    this.$el.appendChild(this.render.domElement)
      // window.addEventListener('resize', this.onWindowResize) //监听窗口变化

      this.render = new THREE.WebGLRenderer({
        antialias: true

        // logarithmicDepthBuffer: true
      })
      this.render.setClearColor(0xaaaaaa)
      this.render.setPixelRatio(window.devicePixelRatio * 2)
      this.render.setSize(window.innerWidth, window.innerHeight)
      this.render.shadowMap.enabled = true
      this.render.shadowMap.type = THREE.PCFSoftShadowMap

      this.render.toneMapping = THREE.ACESFilmicToneMapping
      this.render.toneMappingExposure = 1.2
      // this.render.outputEncoding = THREE.LinearSRGBColorSpace

      this.render.outputColorSpace = THREE.SRGBColorSpace

      this.$el.appendChild(this.render.domElement)
      window.addEventListener('resize', this.onWindowResize) //监听窗口变化
    },
    //根据屏幕尺寸变化自适应
    onWindowResize() {
      //浏览器窗口大小改变后重新计算
      this.maincontWidth = this.$el.offsetWidth
      this.maincontHeight = this.$el.offsetHeight
      this.maincontSc = this.maincontWidth / this.maincontHeight
      this.camera.aspect = this.maincontSc
      this.camera.updateProjectionMatrix()
      this.render.setSize(this.maincontWidth, this.maincontHeight)
    }, //鼠标移动6+射线拾取
    //初始化控制器
    initCotronl() {
      this.mouse = new THREE.Vector2() //获取鼠标 位置二维坐标信息
      document.body.addEventListener('mousemove', this.onDocumentMouseMove)
      document.body.addEventListener('mousedown', this.onDocumentMouseDown)
      this.$el.addEventListener('mouseup', this.onDocumentMouseUp)
    }, //初始化物体
    initFile() {
      this.$emit('loadingfn', true)
      let gltfloader = new GLTFLoader()
      this.app = gltfloader
      const dracoLoader = new DRACOLoader()
      // dracoLoader.setDecoderPath('/draco/')
      dracoLoader.setDecoderPath(
        'http://zfatt.oss-cn-beijing.aliyuncs.com/threejs/draco/'
      )
      dracoLoader.preload()
      gltfloader.setDRACOLoader(dracoLoader)
      gltfloader.load(this.baseUrl + 'DRZhiKong_CJ.glb', (gltf) => {
        this.model = gltf.scene
        this.objectReItem = gltf.scene
        gltf.scene.position.set(0, 0, 0)
        this.objects = []
        gltf.scene.traverse((child) => {
          if (child.isMesh) {
            // child.receiveShadow = true
            // child.castShadow = true
            child.material.emissiveMap = child.material.map
            if (this.objectNames.includes(child.name)) {
              //将需要检查到的模型放到objects
              this.objects.push(child)
              console.log('当前可以戳摸的模型', this.objects)
            }
            if (child.name == 'DR7_2') {
              this.DR7_2 = child
            }
          }
        })
        this.scene.add(gltf.scene)

        // this.$emit('loadingfn', false);
        this.animate()
        this.render.render(this.scene, this.camera)
      })
    },
    // initGUI() {
    //   this.gui = new dat.GUI()
    //   // 将参数添加到GUI中，并指定范围和步长
    //   const folder = this.gui.addFolder('Planes Position')
    //   folder
    //     .add(this.params, 'topPlaneX', -2, 2)
    //     .name('Top Plane X')
    //     .onChange(this.updatePosition)
    //   folder
    //     .add(this.params, 'topPlaneY', -2, 2)
    //     .name('Top Plane Y')
    //     .onChange(this.updatePosition)
    //   folder
    //     .add(this.params, 'topPlaneZ', -2, 2)
    //     .name('Top Plane Z')
    //     .onChange(this.updatePosition)
    //   folder
    //     .add(this.params, 'bottomPlaneX', -2, 2)
    //     .name('Bottom Plane X')
    //     .onChange(this.updatePosition)
    //   folder
    //     .add(this.params, 'bottomPlaneY', -2, 2)
    //     .name('Bottom Plane Y')
    //     .onChange(this.updatePosition)
    //   folder
    //     .add(this.params, 'bottomPlaneZ', -2, 2)
    //     .name('Bottom Plane Z')
    //     .onChange(this.updatePosition)
    //   folder.open()
    // },
    updatePosition() {
      console.log('更新了平面位置及信息啦')
      // 更新顶部和底部平面的位置
      this.geometryTop.translate(
        this.params.topPlaneX,
        this.params.topPlaneY,
        this.params.topPlaneZ
      )
      this.geometryBottom.translate(
        this.params.bottomPlaneX,
        this.params.bottomPlaneY,
        this.params.bottomPlaneZ
      )
      // 重新渲染场景或者刷新应用程序
      this.animate()
    },
    getTop() {
      // var that = this;
      var material = new THREE.MeshBasicMaterial({
        color: 0x00d1ff,
        side: THREE.DoubleSide,
        transparent: true, // 设置为true，opacity才会生效
        opacity: 0.2,
        depthWrite: false // 不遮挡后面的模型
      })

      var geometryTop = new THREE.PlaneGeometry(0.1, 0.1)
      geometryTop.rotateX(Math.PI * 0.5)
      this.geometryTop = geometryTop
      // geometryTop.translate(-0.684, 1.35, -0.050)
      this.geometryTop.translate(
        this.params.topPlaneX,
        this.params.topPlaneY,
        this.params.topPlaneZ
      )
      var planeTop = new THREE.Mesh(this.geometryTop, material)
      this.scene.add(planeTop)
      this.planeTop = planeTop
      this.getLine(true)
    },
    getLine(init) {
      // if(!init) {
      // 	this.cylinder.removeFromParent();
      // 	this.planeBottom.removeFromParent();
      //   }
      if (this.cylinder && this.planeBottom) {
        this.cylinder.removeFromParent()
        this.planeBottom.removeFromParent()
      }

      // var that = this;
      var material = new THREE.MeshBasicMaterial({
        color: 0x00d1ff,
        side: THREE.DoubleSide,
        transparent: true, // 设置为true，opacity才会生效
        opacity: 0.2,
        depthWrite: false // 不遮挡后面的模型
      })

      var boxHeight = 0.1 * this.theHeight + 0.1
      var boxWidth = 0.1 * this.theWidth + 0.1
      var geometryBottom = new THREE.PlaneGeometry(boxWidth, boxHeight)
      geometryBottom.rotateX(Math.PI * 0.5)
      // geometryBottom.translate(-0.684, 0.84, -0.050);
      this.geometryBottom = geometryBottom
      this.geometryBottom.translate(
        this.params.bottomPlaneX,
        this.params.bottomPlaneY,
        this.params.bottomPlaneZ
      )
      var planeBottom = new THREE.Mesh(this.geometryBottom, material)
      this.scene.add(planeBottom)
      this.planeBottom = planeBottom
      this.planeBottom.visible = false
      console.log('planeBottom', planeBottom)

      var geometryTopArr = this.planeTop.geometry.getAttribute('position').array
      var geometryBottomArr =
        this.planeBottom.geometry.getAttribute('position').array
      var verticesArr = this.getAll(geometryTopArr, geometryBottomArr)
      const geometryNew = new THREE.BufferGeometry()
      const vertices = new Float32Array(verticesArr)
      geometryNew.setAttribute(
        'position',
        new THREE.BufferAttribute(vertices, 3)
      )
      var cylinder = new THREE.Mesh(geometryNew, material)
      if (init) {
        cylinder.visible = false
      }
      this.scene.add(cylinder)

      this.cylinder = cylinder
    },
    getAll(vertices1, vertices2) {
      var that = this
      var verticesAll = []
      var indexArr = [
        [0, 1],
        [1, 3],
        [2, 3],
        [1, 4]
      ]
      for (var i = 0; i < indexArr.length; i++) {
        var start = indexArr[i][0]
        var end = indexArr[i][1]
        var endAll = indexArr[i][1] == 3 ? false : true
        var point1 = vertices1.slice(start * 3, (start + 1) * 3)
        var point2 = endAll
          ? vertices1.slice(end * 3, (end + 1) * 3)
          : vertices1.slice(end * 3)
        var point3 = vertices2.slice(start * 3, (start + 1) * 3)
        var point4 = endAll
          ? vertices2.slice(end * 3, (end + 1) * 3)
          : vertices2.slice(end * 3)
        var itemArr = that.getOne(point1, point2, point3, point4)
        verticesAll = [...verticesAll, ...itemArr]
      }
      return verticesAll
    },
    getOne(point1, point2, point3, point4) {
      var newArr = [
        ...point1,
        ...point2,
        ...point3,
        ...point2,
        ...point3,
        ...point4,
        ...point3,
        ...point4,
        ...point1,
        ...point4,
        ...point1,
        ...point2
      ]
      return newArr
    },
    destroyOldScene() {
      if (this.objectFather) {
        this.scene.remove(this.objectFather.scene)
        this.objectFather.scene.traverse((child) => {
          if (child.material) {
            child.material.dispose()
          }
          if (child.geometry) {
            child.geometry.dispose()
          }
          child = null
        })

        this.objectFather = null
      }
    },
    //根据步骤渲染物体和动画
    initFileS(index) {
      this.$emit('loadingfn', true)

      let gltfloader = new GLTFLoader()
      const dracoLoader = new DRACOLoader()
      // dracoLoader.setDecoderPath('/draco/')
      dracoLoader.setDecoderPath(
        'http://zfatt.oss-cn-beijing.aliyuncs.com/threejs/draco/'
      )
      dracoLoader.preload()
      gltfloader.setDRACOLoader(dracoLoader)
      gltfloader.load(this.baseUrl + this.dhfiles[index], (gltf) => {
        this.destroyOldScene()

        if (this.worldOctree) {
          this.worldOctree.fromGraphNode(gltf.scene)
        }
        gltf.scene.position.set(0, 0, 0)
        // this.objects = []
        gltf.scene.traverse((child) => {
          if (child.isMesh) {
            child.castShadow = false
            child.receiveShadow = true
            child.castShadow = true
            if (this.objectNames.includes(child.name)) {
              //将需要检查到的模型放到objects
              this.objects.push(child)
            }

            child.material.emissiveMap = child.material.map
            // child.material.emissive = child.material.color
          }
        })
        this.scene.add(gltf.scene)
        this.objectFather = gltf
        this.andh = gltf.animations
        console.log('动画数据', gltf.animations)
        this.render.render(this.scene, this.camera)

        this.$emit('loadingfn', false)

        // this.initDragControls(this.Farray) //初始化拖拽控制器
      })
    },

    //初始化灯光
    initLight() {
      const ambientLight = new THREE.AmbientLight(0xffffff, 1)
      this.scene.add(ambientLight)
      const directionalLight1 = new THREE.DirectionalLight(0xffffff, 0.36)
      // directionalLight1.position.set(0.5, 2, 1);
      directionalLight1.position.set(0.05, -0.65, 2.7)
      directionalLight1.castShadow = true
      this.scene.add(directionalLight1)
      const directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.34)
      directionalLight2.position.set(-11.2, -4.6, -2)
      directionalLight2.castShadow = false
      this.scene.add(directionalLight2)
      const directionalLight3 = new THREE.DirectionalLight(0xffffff, 0.3)
      directionalLight3.position.set(0.5, 1.6, -3)
      directionalLight3.castShadow = true
      this.scene.add(directionalLight3)
      // 	const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
      // this.scene.add(ambientLight);
      // const directionalLight1 = new THREE.DirectionalLight(0xffffff, 0.5);
      // directionalLight1.position.set(0.5, 2, 1);
      // directionalLight1.castShadow = true;
      // this.scene.add(directionalLight1);
      // const directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.3);
      // directionalLight2.position.set(-1, 5, -9);
      // directionalLight2.castShadow = false;
      // this.scene.add(directionalLight2);
      // const directionalLight3 = new THREE.DirectionalLight(0xffffff, 0.2);
      // directionalLight3.position.set(-1, 2, -3);
      // directionalLight3.castShadow = true;
      // this.scene.add(directionalLight3);
    },
    initPoint() {
      //初始换加载箭头指示图标
      const spriteImageLabel = (image) => {
        let textureLoader = new THREE.TextureLoader()
        const imageTexture = textureLoader.load(image)
        return imageTexture
      }
      let imgUrl = require('@/images/pointer.png')
      const spriteMap = spriteImageLabel(imgUrl)
      const spriteMaterial = new THREE.SpriteMaterial({
        map: spriteMap,
        color: 0xffffff
      })
      const sprite = new THREE.Sprite(spriteMaterial)
      sprite.scale.set(0.1, 0.1, 0.1)
      sprite.rotation.set(0, 0, Math.PI * 0.6)
      sprite.visible = false
      this.sprite = sprite
      this.scene.add(sprite)
    },
    //根据按钮播发动画
    playAction(animationName, realName) {
      console.log('播放了动画名称', animationName, '点击的物体', realName)
      this.playIng = true
      const theMixer = new THREE.AnimationMixer(this.objectFather.scene) //动画的物体
      const clip = THREE.AnimationClip.findByName(
        this.objectFather.animations,
        animationName
      ) //要播放的动画名称
      const action = theMixer.clipAction(clip)
      action.loop = THREE.LoopOnce //动画只执行一次
      action.clampWhenFinished = true //播放完成之后自动结束
      action.play()
      this.action = action
      theMixer.addEventListener('finished', () => {
        return setTimeout(() => {
          this.playIng = false
          this.clickItem(realName)
          // this.$emit('clickItem', realName)
          console.log('动画播放完成')
        }, 600)
      })
      this.theMixer = theMixer
    },
   
    //循环渲染
    //循环渲染
    animate() {
      if (this.isDestroyed || !this.render) { 
        return
      }
      const deltaTime = this.clock.getDelta()
      if (this.theMixer) {
        //动画渲染  3000 控制动画没一帧之间的时长
        this.theMixer.update(deltaTime )
        // this.clock.getDelta()
      }
     this.animationFrameId= requestAnimationFrame(this.animate)
       this.render.render(this.scene, this.camera)
    },
    //镜头移动视角切换根据不同的步骤进行操作
    move(position, rotation) {
      if (!this.camera) {
        return
      }
      // this.controls.enabled = false
      this.camera.position.set(position[0], position[1], position[2])
      this.camera.rotation.set(
        rotation[0] * Math.PI,
        rotation[1] * Math.PI,
        rotation[2] * Math.PI
      )
      this.camera.updateProjectionMatrix()
    },
    //按照坐标位置显示指示箭头
    twinklePoint(x, y, z) {
      if (this.sprite) {
        this.sprite.visible = true
        this.sprite.position.set(x, y, z)
        this.spriteTimer = setInterval(() => {
          this.sprite.visible = !this.sprite.visible
        }, 600)
      }
    },
    getTextName(realName) {
      //根据模型名称返回对应汉字
      let textName = ''
      this.objectText.map((item) => {
        if (item.name == realName) {
          textName = item.text
        }
      })
      return textName
    },

    //获取名字
    getRealName(object) {
      //根据模型返回其父级group的名称，且之后在objects中存在的才会返回名称
      let objectNames = this.objectNames
      if (objectNames.includes(object.name)) {
        return object.name
      } else {
        if (object.parent) {
          return this.getRealName(object.parent)
        } else {
          return ''
        }
      }
    },
    //鼠标移动6+射线拾取
    onDocumentMouseMove(event) {
      //鼠标移动，用射线检测鼠标覆盖的东西，并弹出标识
      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      this.mouse.x = (event.offsetX / maincontWidth) * 2 - 1
      this.mouse.y = -(event.offsetY / maincontHeight) * 2 + 1
      this.raycaster.setFromCamera(this.mouse, this.camera)
      // console.log('当前检测到', this.objects)

      const intersections = this.raycaster.intersectObjects(this.objects)

      if (intersections.length > 0) {
        document.body.style.cursor = 'pointer'
        let textName = this.getTextName(
          this.getRealName(intersections[0].object)
        )
        this.tipShow = true
        this.tipPosition = {
          x: event.offsetX,
          y: event.offsetY
        }
        this.tipName = textName
      } else {
        document.body.style.cursor = 'initial'
        this.tipShow = false
        this.tipPosition = {
          x: event.offsetX,
          y: event.offsetY
        }
        this.tipName = ''
        this.selectedObjects = []
      }
    },

    //清除指示箭头
    clearPoint() {
      console.log('清楚箭头', this.sprite.visible)
      if (this.sprite) {
        console.log('清楚箭头', this.sprite.visible)
        this.sprite.visible = false
      }
      if (this.spriteTimer) {
        clearInterval(this.spriteTimer)
        this.spriteTimer = null
      }
    },
    //鼠标按下播放动画
    onDocumentMouseDown(event) {
      //鼠标移动，用射线检测鼠标覆盖的东西，并弹出标识

      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      this.mouse.x = (event.offsetX / maincontWidth) * 2 - 1
      this.mouse.y = -(event.offsetY / maincontHeight) * 2 + 1
      this.raycaster.setFromCamera(this.mouse, this.camera)
      const intersections = this.raycaster.intersectObjects(this.objects)
      if (intersections.length > 0) {
        document.body.style.cursor = 'pointer'
        if (intersections[0].object.name == this.jcname) {
          // this.addOutinesss('')
          document.exitPointerLock()
        }
        this.clickAfter(intersections[0].object.name)
      }
      if (document.pointerLockElement) {
        event.preventDefault()
      } else {
        // if (this.setp == 1.2 || this.setp == 1.3) {
        //   if (event.target.localName == 'canvas') {
        //     document.body.requestPointerLock()
        //   }
        // }
      }
    },
    //根据点击的模型播放动画
    clickAfter(realName) {
      console.log('当前点击的模型', realName)
      this.twinklePoint(-3, -3, -3)
      // 动画还没加载完的情况
      if (!this.andh) {
        console.log('当前没有动画数据')
        if (this.action) {
          this.action.stop()
          this.action.paused = true
        }
        this.action = null
        return
      }
      if (this.playIng) {
        // this.step
        if (!this.playIng) {
          console.log('当前任务还未完成禁止下一个')
        } else {
          return
        }
      }
      let animationName = ''
      if (realName == 'TanCeQi4' && this.taskids == 3) {
        animationName = '2'
        this.playIng = true
      }
      if (
        realName == 'ShiYanShi1_3' ||
        realName == 'ShiYanShi1_2' ||
        realName == 'ShiYanShi1_4'
      ) {
        this.$nextTick(() => {
          this.taskids = 6.2
        })
      }
      if (!animationName) {
        // console.log('dh')
        console.log('未指定播放动画', animationName, '当前小步骤', this.eritems)
        return
      }

      this.clearPoint()
      this.playAction(animationName, realName)
    }
  }
}
